/**
 * 我的企业信息
 */
var extensions = {};
$(function(){
	initialExtensions();//初始化企业扩展信息表单信息
	getInfo();
	
	$("#uploadFile1,#uploadFile2,#uploadFile3,#uploadFile4").change(function(){
		$id=$(this).attr('data-id');
			$name="#p"+$id + " span";
		if($($name).length>2){
			alert("图片最多三张");
		}else{
			uploadSpaceImage($id);
		}
	});
	
	$("#btnSave").click(btnsave);
})

function getInfo(){
	$.ajax({
        url: '/euc/center/member/getClientInfos',
        data:'',
        beforeSend: function(request) {
        	var memberToken = localStorage.getItem('memberToken');
            request.setRequestHeader("token",memberToken );
        },
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'GET',
        success: function (result, textStatus, response) {
        	if(result.message=='获取成功'){
        		v=result.data;
        		$("input[name='companyName']").val(v.companyName);
        		$("select[name='clientType']").val(v.clientType);
        		$("#customerType").val(v.customerType);
        		$("input[name='companyAddress']").val(v.companyAddress);
        		$("input[name='companyLegalPerson']").val(v.companyLegalPerson);//法人
        		$("input[name='companyRegisteredCapital']").val(v.companyRegisteredCapital);
				$("input[name='companyCreditCode']").val(v.companyCreditCode);//信用
        		$("input[name='companyRealCapital']").val(v.companyRealCapital);
        		$("select[name='companyEnterpriseType']").val(v.companyEnterpriseType);
        		$("input[name='companyCreateDate']").val(v.companyCreateDate);
        		$("input[name='companyBusiness']").val(v.companyBusiness);
        		$("input[name='companyBusinessScope']").val(v.companyBusinessScope);
        		$("input[name='companyCreditCode']").val(v.companyCreditCode);
        		$("textarea[name='remark']").val(v.remark);//备注
        		$("input[name='companyLegalPerson1']").val(v.companyLegalPerson);//主联系人
        		$("#qy_lianxi").val(v.mainContacter);
        		$("#qy_phone").val(v.enterprisePhone);//企业电话
        		
        		/*$.each(v.clientExtensionList,function(i,data){			
        			data.extensionId==1 && $("#qy_suoshu").val(data.extension);
        			data.extensionId==2 && $("#qy_url").val(data.extension) ;
        			data.extensionId==3 && $("#qy_mobile").val(data.extension) ;
        			data.extensionId==4 && $("#qy_guimo").val(data.extension);
        			data.extensionId==5 && $("#qy_jieshao").val(data.extension);
    			});
        		*/
        		try{
        			$.each(v.clientExtensionList,function(i,data){
        				$("[formParameter='extension'][name='extension"+data.extensionId+"']").val(data.extension);
        			});
        		}catch(e){
        			console.log(e.message);
        		}
    	    	//资质
        		if(v.enterpriseAuthority&&v.enterpriseAuthority!='null'){
        			
        		
        			if(v.enterpriseAuthority.indexOf(",")!=-1){
        				var $imgs =v.enterpriseAuthority.split(',');
						$("#p1").html('');
        				$.each($imgs,function(m,n){
        					$("#p1").append('<span data-url="'+n+'" onclick="del(this)"><img src="'+n+'">删除</span>');
        				})
        				
        			}else{
        				$("#p1").html('<span data-url="'+v.enterpriseAuthority+'" onclick="del(this)"><img src="'+v.enterpriseAuthority+'">删除</span>');
        			}        			
        		}
    	    	//法人
        		if(v.ownerIdCard&&v.ownerIdCard!='null'){
        			if(v.ownerIdCard.indexOf(',')!=-1){
        				var $imgs =v.ownerIdCard.split(',');
						$("#p2").html('');
        				$.each($imgs,function(m,n){
        					$("#p2").append('<span data-url="'+n+'" onclick="del(this)"><img src="'+n+'">删除</span>');
        				})
        				
        			}else{
        				$("#p2").html('<span data-url="'+v.ownerIdCard+'" onclick="del(this)"><img src="'+v.ownerIdCard+'">删除</span>');
        			}        			
        		}
    	    	//个人
        		if(v.personalIdCard&&v.personalIdCard!='null'){
        			if(v.personalIdCard.indexOf(',')!=-1){
        				var $imgs =v.personalIdCard.split(',');
						$("#p3").html('');
        				$.each($imgs,function(m,n){
        					$("#p3").append('<span data-url="'+n+'" onclick="del(this)"><img src="'+n+'">删除</span>');
        				})
        				
        			}else{
        				$("#p3").html('<span data-url="'+v.personalIdCard+'" onclick="del(this)"><img src="'+v.personalIdCard+'">删除</span>');
        			}        			
        		}
    	    	//logo
        		if(v.logoUrl&&v.logoUrl!='null'){
        			if(v.logoUrl.indexOf(',')!=-1){
        				var $imgs =v.logoUrl.split(',');
						$("#p4").html('');
        				$.each($imgs,function(m,n){
        					$("#p4").append('<span data-url="'+n+'" onclick="del(this)"><img src="'+n+'">删除</span>');
        				})
        				
        			}else{
        				$("#p4").html('<span data-url="'+v.logoUrl+'" onclick="del(this)"><img src="'+v.logoUrl+'">删除</span>');
        			}        			
        		}
        		
        	}
        	
        },
        error: function () {
        	/*alert("error");*/
        }  
    });
}

function uploadSpaceImage(id){

    var accessToken = localStorage.getItem('memberToken');
    $fname='#headForm'+id;
    $($fname).ajaxSubmit({
        dataType : "json",
        headers : {'Access-Control-Allow-Origin':'*',"token":accessToken},
        beforeSubmit : function(request) {
            //alert("正在上传");
        },
        success : function(result, textStatus, response) {
        	if(result.status==0){
            	$name="#p"+id;
                $($name).append('<span data-url="'+result.data+'" onclick="del(this)"><img src="'+result.data+'">删除</span>');
        	}else{
        		alert(result.message);
        	}


        },
        error : function(result) {
            alert(result.message);

        }
    });
}

function del(obj){
	 obj.parentNode.removeChild(obj);
}

function btnsave(){
	var data={};
	data.companyName =$("input[name='companyName']").val();
	data.clientType =$("select[name='clientType']").val();
	data.customerType =$("#customerType").val();
	data.companyAddress =$("input[name='companyAddress']").val();
	data.companyLegalPerson =$("input[name='companyLegalPerson']").val();//法人
	data.companyRegisteredCapital = $("input[name='companyRegisteredCapital']").val();
	data.companyCreditCode = $("input[name='companyCreditCode']").val();//信用证
	data.companyRealCapital = $("input[name='companyRealCapital']").val();
	data.companyEnterpriseType = $("select[name='companyEnterpriseType']").val();
	data.companyCreateDate = $("input[name='companyCreateDate']").val();
	data.companyBusiness = $("input[name='companyBusiness']").val();
	data.companyBusinessScope = $("input[name='companyBusinessScope']").val();

	data.remark = $("textarea[name='remark']").val();//备注
	//data.companyLegalPerson =$("input[name='companyLegalPerson1']").val();//主联系人
	
	$("#qy_suoshu").val();//所属
	data.mainContacter =$("#qy_lianxi").val();
	data.enterprisePhone =$("#qy_phone").val();//企业电话
	
	var clientExtensionList = data.clientExtensionList;
	try{			
		if(clientExtensionList == null){
			clientExtensionList = [];
		}
		var clientType = "企业";
		$("[formParameter='extension'][name^='extension']").each(function(index,element){
			if("企业" == clientType){
				var required = $(element).prop("required");
				var val =  $(element).val();
				if((required == '1' || required == true)  && ($.trim(val) == '' || $.trim(val) == '0')){				
					var message = $(element).attr("message");
					alert(message);
					clue = false;
					return false;
				}
			}
			if($(element).val() == '请选择'&&"企业" == clientType){
				alert("请选择所属行业");return false;
			}
			var extensionId = $(element).attr("extensionId");
			var clientExtension = null;
			var index = -1;
			$.each(clientExtensionList,function(i,data){
				if(data.extensionId == extensionId){
					index = i;
					clientExtension = data;
				}
			});
			if(null == clientExtension){
				clientExtension = {};
			}
			clientExtension['extensionId'] = extensionId;
			clientExtension['extension'] = $(element).val();
			if(-1 == index){
				clientExtensionList[clientExtensionList.length] = clientExtension;					
			}else{
				clientExtensionList[index] = clientExtension;
			}
		});
		data.clientExtensionList = clientExtensionList;
	}catch(e){
		console.log(e.message);
	}
	
	
	data.enterpriseAuthority=getpic(1);
	data.ownerIdCard=getpic(2);
	data.personalIdCard=getpic(3);
	data.logoUrl=getpic(4);
	
	$.ajax({
        url: '/euc/center/member/updateClientInfos',
        data:JSON.stringify(data),
        beforeSend: function(request) {
        	var memberToken = localStorage.getItem('memberToken');
            request.setRequestHeader("token",memberToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	//alert(JSON.stringify(result));
			if(result.status === 0){
        		alert("修改成功");
        		 window.location.reload();
        	}else{
        		alert(result.message);
        	}
        },
        error: function () {
        	console.log("error");
        }  
    });

}

function getpic(id){
	$name="#p"+id +" span";
	num = $($name).length;
	if(num>0){
		if(num==1){
			return $($name).attr('data-url');
		}else{
			$pic = new Array();
			for (i=0;i<num;i++) {
				
				$pic[i]=$($name)[i].getAttribute('data-url');
			}
			return $pic.toString();
			
		}
	}else{
		return '';
	}
	
}


function initialExtensions(){//初始化企业扩展信息字段表单
	$.ajax({
        url: '/euc/center/member/extension/list',
        data:'',
        beforeSend: function(request) {
          	var memberToken = localStorage.getItem('memberToken');
            request.setRequestHeader("token",memberToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	//alert(JSON.stringify(result));
	        var extensionDiv = $("#clientExtensions");
	        $(extensionDiv).empty();
	        $('<div class="formtitle "><span>企业扩展信息</span></div>').appendTo($(extensionDiv));	        
	    	$.each(result,function(i,data){
	    		var html = '';
	    		if(data.id==1){//指定所属行业
    				html += '<ul class="forminfo"  clientType="企业"><li><label >所属行业</label>';
    				html += '<select extensionId = "1" name="extension1" class="incinput"  message="请选择所属行业" formParameter="extension" >';
    				html += '<option value="请选择" selected="selected">请选择</option>';
					html += '<option value="互联网科技">互联网科技</option>';
					html += '<option value="贸易">贸易</option>';
					html += '<option value="金融">金融</option>';
					html += '<option value="电商平台">电商平台</option>';
					html += '<option value="企业服务">企业服务</option>';
					html += '<option value="软件开发">软件开发</option>';
					html += '<option value="品牌设计">品牌设计</option>';
					html += '<option value="营销推广">营销推广</option>';
					html += '<option value="影视动漫">影视动漫</option>';
					html += '<option value="其他">其他</option>';
    				html += '</select> </li> </ul>';
    			}else{
		    		if(data.contentLength <= 50){
		    			html += '<ul class="forminfo"  clientType="企业">';
		    			html += '<li><label >'+data.extensionName;
		    			if(data.required == '是'){
		    				html += '<b>*</b></label><input required = "1" message="请输入' + data.extensionName + '" ';
		    			}else{
		    				html += '</label><input '; 
		    			}
		    			html += '  extensionId = "' + data.id + '" ';
		    			html += '  name="extension'+data.id+'" type="text" class="incinput" ';
		    			html += '  formParameter="extension" placeholder= "请输入' + data.extensionName + '" /></li></ul>'; 
		    		}else if(data.contentLength <= 100){
		    			html += '<ul class="forminfo" clientType="企业">';
		    			html += '<li><label>'+data.extensionName;
		    			if(data.required == '是'){
		    				html += '<b>*</b></label><input required = "1" message="请输入' + data.extensionName + '" ';
		    			}else{
		    				html += '</label><input '; 
		    			}
		    			html += '  extensionId = "' + data.id + '" ';
		    			html += '  name="extension'+data.id+'" type="text" class="indinput" style="width:677px;" ';
		    			html += '  formParameter="extension" placeholder= "请输入' + data.extensionName + '" /></li></ul>'; 
		    		}else{
		    			html += '<ul class="forminfo"  clientType="企业">';
		    			html += '<li><label >'+data.extensionName;
		    			if(data.required == '是'){
		    				html += '<b>*</b></label><textarea  required = "1" message="请输入' + data.extensionName + '" ';
		    			}else{
		    				html += '</label><textarea  ';
		    			}
		    			html += '  extensionId = "' + data.id + '" ';
		    			html += '  name="extension'+data.id+'" cols="" rows="" class="langtext"  ';
		    			html += '  formParameter="extension" placeholder= "请输入' + data.extensionName + '"></textarea></li></ul>'; 
		    		}
    			}
	    		$(extensionDiv).append(html);
	    		extensions[data.id] = data;
			});
	    	if(result.length > 0){
	    		$("#clientExtensions").show();
	    	}
        },
        error: function () {
        	console.log("/euc/extension/list error");
        }  
    });
}
